package com.nirvana.generate;

import com.intellij.openapi.ui.Messages;
import com.nirvana.config.PluginConfig;
import com.nirvana.convert.CamelCaseConverter;
import com.nirvana.factory.ItemFactory;
import com.nirvana.item.CommonItem;
import com.nirvana.type.ItemType;
import org.apache.commons.lang3.StringUtils;

public class InitCodeGenerator implements GenerateInterface {
    private static InitCodeGenerator INSTANCE;

    private InitCodeGenerator() {

    }

    public static InitCodeGenerator getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new InitCodeGenerator();
        }
        return INSTANCE;
    }

    @Override
    public void generate() {
        CommonItem defPropertyCommonItem = ItemFactory.getCommonItem(ItemType.DefPropertyItem);
        String className = defPropertyCommonItem.textField.getText();
        if (StringUtils.isBlank(className)) {
            Messages.showErrorDialog("配置类名不能为空", "生成加载代码错误");
            return;
        }
        int index = className.indexOf("Def");
        String element = index > 0 ? className.substring(0, index) : className;
        String method;
        if (PluginConfig.getInstance().useFlatBuffers()) {
            method = "%sBase.load()".formatted(className);
        }else {
            method = "loadXmlToClassNew[%s](\"%s\")".formatted(
                    className,
                    CamelCaseConverter.camelToSnakeCase(element)
            );
        }
        String content = """
                private def load%s(): Unit = {
                    %s.foreach(_def => {
                
                    })
                }
                """.formatted(
                        CamelCaseConverter.toCamelCase(element, false),
                        method
        );
        defPropertyCommonItem.mainPanel.initCodeTextField.setText(content);
    }
}
